package com.shell.governor.organization.service.impl;

import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.bee.persistence.service.impl.PersistentServiceImpl;
import com.shell.governor.organization.dao.PubStruDao;
import com.shell.governor.organization.po.PubStru;
import com.shell.governor.organization.service.PubStruService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PubStruServiceImpl extends PersistentServiceImpl<PubStru> implements PubStruService {
	@Autowired
	private PubStruDao pubStruDao;

	public int savePubStruRecord(PubStru pubStru) {
		int result = 0;
		if (pubStru != null) {
			PubStru pubStruTemp = new PubStru();
			pubStruTemp.setOrganId(pubStru.getOrganId());
			deleteEntity(pubStruTemp);
			if (StringUtil.emptyAndNull(pubStru.getStruId())) {
				pubStru.setStruId(SystemUtil.getUUID());
			}
			if (StringUtil.emptyAndNull(pubStru.getStruType())) {
				pubStru.setStruType("0");
			}
			if (StringUtil.notTrimEmpty(pubStru.getParentId())) {
				PubStru parent = new PubStru();
				parent.setOrganId(pubStru.getParentId());
				parent = (PubStru) this.pubStruDao.selectOne(parent);
				if (parent != null) {
					String path = parent.getStruPath() + ";" + pubStru.getOrganId();
					pubStru.setStruPath(path);
					pubStru.setStruLevel(Integer.valueOf(parent.getStruLevel().intValue() + 1));
				}
			} else {
				pubStru.setStruPath(pubStru.getOrganId());
			}
			result = this.pubStruDao.insert(pubStru);
		}
		return result;
	}

	public int modifyPubStruRecord(PubStru pubStru) {
		int result = 0;
		if (pubStru != null) {
			PubStru old = new PubStru();
			old.setOrganId(pubStru.getOrganId());
			old = (PubStru) this.pubStruDao.selectOne(old);
			if (old != null) {
				if (StringUtil.notEmpty(pubStru.getStruType())) {
					old.setStruType(pubStru.getStruType());
				}
				if ((StringUtil.notEmpty(pubStru.getParentId())) && (pubStru.getStruLevel().intValue() > 0)) {
					old.setParentId(pubStru.getParentId());
					PubStru parent = new PubStru();
					parent.setOrganId(pubStru.getParentId());
					parent = (PubStru) this.pubStruDao.selectOne(parent);
					if (parent != null) {
						String path = parent.getStruPath() + ";" + pubStru.getStruId();
						old.setStruPath(path);
					}
				} else {
					old.setStruPath(pubStru.getOrganId());
				}
				result = this.pubStruDao.updateByPrimaryKey(old);
			}
		}
		return result;
	}
}
